<template>
  <div>
    <el-dialog v-model="model" :title="type=='ADD'?'添加标签':'编辑标签'" width="500" :close-on-click-modal="false">
      <el-form :model="form" label-width="110" :rules="rules" ref="formRef">
        <el-form-item label="选择标签图片" prop="username">
          <el-upload
            class="avatar-uploader"
            :action="`http://127.0.0.1:7001/admin/file`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.tag_img" :src="form.tag_img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="图片路径" prop="tag_img">
          <el-input v-model="form.tag_img" :disabled="true"/>
        </el-form-item>
        <el-form-item label="标签名" prop="tag_name">
          <el-input v-model="form.tag_name" />
        </el-form-item>
        <el-form-item label="备注" prop="tag_describe">
          <el-input v-model="form.tag_describe" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)">
            {{type=='ADD'?'添加':'修改'}}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import router from '@/router'
import { moduleExpression } from '@babel/types'
import { Plus } from '@element-plus/icons-vue'
import user from '@/config/Enums/user'
import Pinterface from '@/config/Interface/Public'
import Interface from '@/config/Interface/User'
import { defineComponent,ref,onMounted,reactive,toRefs} from 'vue'
import { getCurrentInstance} from 'vue'
import { useStore } from '../../store'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { createTagsApi,updateTagsApi } from '@/request/tag'
import type { UploadProps } from 'element-plus'
export default defineComponent({
  name: 'addUser',
  components: {

  },
  setup(props,{ emit }){
    const store = useStore()
    const context = getCurrentInstance()?.appContext.config.globalProperties; //获取this
    const msg = reactive<any>({})
    const model =ref(false) // 模态框显示隐藏
    const type = ref('') //类型 添加/编辑

    const reactiveData = reactive({
      form:{
        tag_describe:'',
        tag_name:'',
        tag_img:'',
      },
    })

    const trigger = (Type:string,scope?:any) =>{
      model.value = true
      type.value = Type
      if(scope) {
        msg.value = scope.row
        reactiveData.form.tag_describe = msg.value.tag_describe
        reactiveData.form.tag_name = msg.value.tag_name
        reactiveData.form.tag_img = msg.value.tag_img
      }

    }

    const rules = reactive({
      tag_name:[
        { required: true, message: '请输入标签名', trigger: 'blur' },
        { min: 4, max: 12, message: '标签名长度4-12', trigger: 'blur' },
      ],
      tag_img:[
        { required: true, message: '图片路径不能为空', trigger: 'blur' },
      ],
    })
    // 关闭表单
    const close = () => {
      // reactiveData.form = new Interface.addUserForm()
      model.value = false;
    }
    const formRef = ref<FormInstance>()
    // 提交表单
    const submitForm = async (formEl: FormInstance | undefined) => {
      if (!formEl) {
        return
      }else{
        await formEl.validate((valid, fields) => {
        console.log(valid);
        if (!valid) {
          return
        } else {
          postSend()
        }
      })
      }
    }

    const postSend = async () =>{
      const postData:any = {
        ...reactiveData.form,
      }
      if(type.value =='ADD'){
        const res = await createTagsApi(postData)
        if(res.data.code === 1){
          ElMessage({
            message:"创建成功",
            type:"success"
          })
          close()
          emit('RefreshListEmit')
        }
      }else{
        postData.id = msg.value.id
        const res = await updateTagsApi(postData)
        if(res.data.code === 1){
          ElMessage({
            message:"修改成功",
            type:"success"
          })
          close()
          emit('RefreshListEmit')
        }
      }
    }


    const imageUrl = ref('')

    const handleAvatarSuccess: UploadProps['onSuccess'] = (
      response,
      uploadFile
    ) => {
      imageUrl.value = URL.createObjectURL(uploadFile.raw!)
      reactiveData.form.tag_img = `http://127.0.0.1:7001/public${response.data[0].url}`
    }

    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
      const type = ['image/png','image/jpeg']
      if (!type.includes(rawFile.type)) {
        ElMessage.error('请选择 jpg 或 png 格式的文件')
        return false
      } else if (rawFile.size / 1024 / 1024 > 4) {
        ElMessage.error('图片大小不超过 4MB!')
        return false
      }
      return true
    }

    return {
      ...toRefs(reactiveData),
      model,type,
      trigger,
      rules,
      submitForm,
      close,formRef,
      beforeAvatarUpload,
      handleAvatarSuccess,
      imageUrl
    }
  }
})
</script>

<style scoped lang="stylus">
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  border: 1px solid #dbdbdb
}
</style>
